<template>
  <div class="app">
    name: {{ name }} age: {{ age }}
    <button @click="changeName">changeName</button>
    <button @click="changeAge">changeAge</button>
  </div>
</template>
<script>
//  watchEffect 开启立即执行,并侦听数据
//  watchEffect 参数1 是一个副作用函数
//  watchEffect 返回一个函数的调用，可以用于停止侦听

import { ref, watchEffect } from 'vue'

export default {
  setup() {
    const name = ref('ide')
    const age = ref(18)
    const stop = watchEffect((onCleanup) => {
      const timer = setTimeout(() => {
        console.log('订阅')
      })

      // 清除副作用
      onCleanup(() => {
        console.log('取消订阅')
        clearTimeout(timer)
      })
      console.log(name.value)
      console.log(age.value)
    })

    const changeName = () => {
      name.value = 'code'
    }
    const changeAge = () => {
      age.value++
      if (age.value === 26) {
        stop()
      }
    }

    return {
      name,
      age,
      changeName,
      changeAge
    }
  }
}
</script>
<style lang="scss" scoped></style>
